package com.mti.monitor.util;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * @author dongy
 */
@Slf4j
public class SSHUtil {
    //初始化类内变量
    private int SSH_PORT;
    private String username;
    private String password;
    private String hostip;
    private String charset = "UTF-8";
    private Session session;

    public SSHUtil(String user, String password, String hostip, int port) {
        this.username = user;
        this.password = password;
        this.hostip = hostip;
        this.SSH_PORT = port;
    }

    /*
    连接到指定IP
     */
    public void connect() throws JSchException {
        JSch js = new JSch();
        log.info("=========远程登录服务器{}=========",hostip);
        session = js.getSession(username, hostip, SSH_PORT);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        log.info("=========远程登录服务器成功=========");
    }

    /*
    关闭实例链接
     */
    public void disconnect() {
        log.info("=========退出远程服务器{}=========",hostip);
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
    }

    /*
    执行ssh命令接口
     */
    public void executeCmd(String command) throws JSchException, IOException {
        BufferedReader reader = null;
        Channel channel = null;
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);
        channel.connect();
        InputStream in = channel.getInputStream();
        reader = new BufferedReader(new InputStreamReader(in,
                Charset.forName(charset)));
        String buf = null;
        log.info("=========远程登录服务器执行命令{}" + command + "=========");
        StringBuffer buffer = new StringBuffer();
        while ((buf = reader.readLine()) != null) {
            buffer.append(buf);
            buffer.append("\n");
        }
        //测试结果可返回做正则匹配进行逻辑判断
        log.info("=========远程登录服务器执行命令完成:" + buffer.toString() + "=========");
        channel.disconnect();
    }

   /*
   系统输入下发命令
    *//*
    public static void main(String[] args) throws Exception{
        SSHUtil sshUtil = new SSHUtil("root","woshidigua","192.168.194.128",22);
        sshUtil.connect();
        sshUtil.executeCmd("sh /app/service/run_monitor.sh");
        sshUtil.disconnect();
    }*/
}
